<template>
<div class="field _pics" :class='{disabled: data.readonly}'>
  <label :class="{must: data.is_must}">{{data.label}}</label>
  <div class="field ui ">
    <dropzone v-if='!$store.state.isDetail&&uploadUrl' :id="id" :ref="id"
        v-on:vdropzone-success="showSuccess" @vdropzone-removed-file='removed' :options="dropzoneOptions"></dropzone>
      <!-- <showpics :pics='pics' v-if="isUpdate"></showpics> -->
      <showpics :pics='pics' v-if="imgpre" :imgpre='imgpre' @toRemove='toRemove' @sorted='sorted'></showpics>
  </div>
</div>
</template>

<script>
import tool from 'src/util/tool';
import Dropzone from 'vue2-dropzone'
import 'vue2-dropzone/dist/vue2Dropzone.css'
const IMGPRE = tool.IMGPRE

import showpics from './showpics';

export default {
  data() {
    return {
      uploading: false,
      imgpre: null,
      val: ''
    }
  },
  methods: {
    removed(file, error, xhr) {
      // tool.cl(file, xhr)
    },
    'showSuccess': function(file, res) {
      // tool.cl(file)
      let rs = JSON.parse(file.xhr.responseText)
      let data = rs.data
      // tool.cl(file.xhr.responseText)
      // tool.cl(data)
      // tool.cl(res)
      // console.log('A file was successfully uploaded')
      if (rs.status == tool.RS_OK) {
        this.val = this.val ? (this.val + '|' + data.filename) : data.filename
      }
    },
    //finish image uload
    showBigPic() {
      let img = this.val
      tool.cl(img)
    },
    toRemove(pic) {
      let pics = this.pics
	  pic =  pics.find(str => (str.indexOf(pic)+pic.indexOf(str))>-2)
	  pics.remove(pic)
      this.val = pics.join('|');
    },
    sorted(plist) {
      let pics = plist.map(v => {
        return v.replace(this.imgpre, '')
      });
      this.val = pics.join('|');
    }
  },
  watch: {
    val: function(val, old) {
      let _this = this;
      if (val != old) {
        val = val.split("|").map(img =>{
          if(img.split("/").length<2){
            img = _this.imgpre + img;
          }
          return img;
        }).join("|");
        this.$emit('onchange', {name: this.data.name, value: val})
        // this.$emit('setVo', this.data.name, val)
      }
    }
  },
  components: {
    Dropzone,
    showpics
  },
  computed: {
    dropzoneOptions() {
      return {
        url:this.uploadUrl,
        maxNumberOfFiles:this.maxNumberOfFiles,
        thumbnailHeight:this.thumbnailHeight,
        thumbnailWidth:this.thumbnailWidth,
        maxFileSizeInMB:this.maxFileSizeInMB,
        useFontAwesome:this.useFontAwesome,
        dictDefaultMessage: '<br>图片拖到此处或点击此处上传',
        dictCancelUpload: '取消上传',
        dictCancelUploadConfirmation: '你确定要取消此次上传吗?',
        dictFallbackMessage: '你的浏览器不支持拖拽上传',
        dictFallbackText: 'Please use the fallback form below to upload your files like in the olden days.',
        dictFileTooBig: '文件过大 ({{filesize}}MiB)， 最大尺寸: {{maxFilesize}}MiB',
        dictInvalidFileType: `不支持此类型图片`,
        dictMaxFilesExceeded: '你不能再上传了，（最大数量: {{maxFiles}}）',
        dictRemoveFile: '删除',
        dictRemoveFileConfirmation: null,
        dictResponseError: '服务器返回，code: {{statusCode}} ',
      }
    },
    isUpdate() {
      return this.$store.state.global.op == 'update';
    },
    pics() {
      return this.val ? this.val.split('|') : [];
    },
    placeholder() {
      // return `请选择图片：${this.data.title}`
      return `请选择图片`
    },
    uploadUrl() {
      let url = tool.getApi(this,'Upload', 'uploadPic');
      let param=`?pic_dir=${this.pic_dir}`
      return url+param;
    },
    pic_dir(){
      return this.data.pic_dir == 1 ? 'product' : 'hotel'
    },
    id(){
      return this.data.name + Math.ceil( Math.random() * 1000000 );
    }
  },
  // props: ['field'],
  props: {
    data: {},
    clickable: {
      type: Boolean,
      default: true
    },
    acceptedFileTypes: {
      type: String
    },
    thumbnailHeight: {
      type: Number,
      default: 140
    },
    thumbnailWidth: {
      type: Number,
      default: 140
    },
    showRemoveLink: {
      type: Boolean,
      default: true
    },
    maxFileSizeInMB: {
      type: Number,
      default: 3
    },
    maxNumberOfFiles: {
      type: Number,
      default: 9
    },
    autoProcessQueue: {
      type: Boolean,
      default: true
    },
    useFontAwesome: {
      type: Boolean,
      default: true
    },
    data:{
      type: Object,
      default(){
        return {}
      }
    }
  },
  created() {
    // this.val=this.data.value
    this.imgpre =IMGPRE+'images/'+this.pic_dir+'/';
    this.val = "";
    this.val = this.data.value || "";
  },
  mounted() {
    // $('.ui.shape').shape('flip over');
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
  ._pics{
    position: relative;
    z-index: 0;
  }
</style>
